﻿using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using FrienDev.Data;
using FrienDev.SystemApps;

namespace FrienDev.BusinessRules
{
    public class FriendRules
    {
        public static FriendRules Instance = new FriendRules();

        private FrienDevDataContext m_DataContext = FrienDevDataContext.Instance;

        private FriendRules()
        {
        }

        public List<User> GetFriendsByUserId(string userId)
        {
            IEnumerable<User> users = from f in m_DataContext.Friends
                                      where f.UserId == userId && f.IsAccepted
                                      select f.User;
            return users.ToList<User>();
        }

        public List<User> GetCurrentUserFriends()
        {
            string curUserId;
            curUserId = UserRules.Instance.GetCurrentUserId();
            IEnumerable<User> users = from f in m_DataContext.Friends
                                      where f.UserId == curUserId && f.IsAccepted
                                      select f.FriendUser;
            return users.ToList<User>();
        }

        public object GetCurrentUserFriendsObject()
        {
            string curUserId;
            try
            {
                curUserId = UserRules.Instance.GetCurrentUserId();
            }
            catch
            {
                curUserId = "8c5e14d9c787e9a1756462b4125fbff3";
            }
            var users = from f in m_DataContext.Friends
                        where f.UserId == curUserId && f.IsAccepted
                        select f.User;
            return users;

        }

        public bool IsFriend(string userId, string friendId)
        {
            return IsFriend(userId, friendId, true);
        }

        private bool IsFriend(string userId, string friendId, bool isAccepted)
        {
            IEnumerable<User> users = from f in m_DataContext.Friends
                                      where f.UserId == userId && f.FriendId == friendId && f.IsAccepted == isAccepted
                                      select f.User;
            if (users.Count() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool IsAcceptedFriend(string userId, string friendId)
        {
            IEnumerable<User> users = from f in m_DataContext.Friends
                                      where f.UserId == userId && f.FriendId == friendId && f.IsAccepted
                                      select f.User;
            if (users.Count() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void AddFriend(string userId, string friendId, string request)
        {
            AddFriend(userId, friendId, false, request);
        }

        private void AddFriend(string userId, string friendId, bool isAccepted, string request)
        {
            if (userId == friendId)
            {
                return;
            }
            IEnumerable<User> users = from f in m_DataContext.Friends
                                      where f.UserId == userId && f.FriendId == friendId
                                      select f.User;

            if (users.Count() > 0)  // 如果数据库中已有记录，则更新
            {
                Friend friend = (from f in m_DataContext.Friends
                                 where f.UserId == userId && f.FriendId == friendId
                                 select f).SingleOrDefault();
                if (friend.IsAccepted != isAccepted)
                {
                    friend.IsAccepted = isAccepted;
                    friend.Request = request;
                    m_DataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
                    // 如果是确认添加好友，则添加动态
                    if (isAccepted)
                    {
                        string fullname = UserRules.Instance.GetUserByUserId(friendId).FullName;
                        ApiHelper.Instance.AppendTodayTrack(userId, typeof(FriendApplication), 0,
                            new string[] { friendId, fullname });
                    }
                }
            }
            else // 如果数据库中没有记录，则添加
            {
                Friend friend = new Friend { UserId = userId, FriendId = friendId, IsAccepted = isAccepted, Request = request };
                m_DataContext.Friends.InsertOnSubmit(friend);
                m_DataContext.SubmitChanges();
                // 如果是确认添加好友，则添加动态
                if (isAccepted)
                {
                    string fullname = UserRules.Instance.GetUserByUserId(friendId).FullName;
                    ApiHelper.Instance.AppendTodayTrack(userId, typeof(FriendApplication), 0,
                        new string[] { friendId, fullname });
                }
            }
        }

        public void AcceptFriend(string requestUserId, string myUserId)
        {
            if (requestUserId == myUserId)
            {
                return;
            }
            AddFriend(requestUserId, myUserId, true, "");
            AddFriend(myUserId, requestUserId, true, "");
        }

        /// <summary>
        /// 按照姓名,分页
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="CityName"></param>
        /// <returns></returns>
        public List<User> SearchFriendsByName(string Name,int beginId,int pageSize)
        {

            IEnumerable<User> users = (from u in m_DataContext.Users
                                      where u.FullName.Contains(Name)
                                      select u).Skip(beginId).Take(pageSize);
            return users.ToList<User>();
        }

        /// <summary>
        /// 按照姓名和城市Id搜索好友,分页
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="CityId"></param>
        /// <returns></returns>
        public List<User> SearchFriendsByNameAndCityId(string Name, int CityId,int beginId,int pageSize)
        {
            IEnumerable<User> users = (from u in m_DataContext.Users
                                      where u.FullName.Contains(Name) && u.CityId == CityId
                                      select u).Skip(beginId).Take(pageSize);
            return users.ToList<User>();
        }

        /// <summary>
        /// 得到搜索的朋友总数BY姓名和城市
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="CityId"></param>
        /// <returns></returns>
        public int GetSearchFriendsByNameAndCityIdCount(string Name, int CityId)
        {
            IEnumerable<User> users = (from u in m_DataContext.Users
                                       where u.FullName.Contains(Name) && u.CityId == CityId
                                       select u);
            return users.Count();
        }

        /// <summary>
        /// 得到搜索的朋友总数BY姓名
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="CityId"></param>
        /// <returns></returns>
        public int GetSearchFriendsByNameCount(string Name)
        {
            IEnumerable<User> users = (from u in m_DataContext.Users
                                       where u.FullName.Contains(Name)
                                       select u);
            return users.Count();
        }

        /// <summary>
        /// 获得好友列表——by cciel
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="amount">获取个数,-1为所有</param>
        /// <returns></returns>
        public IEnumerable<User> GetFriendsListByUserId(string userId, int amount)
        {
            IEnumerable<User> friends = from friend in m_DataContext.Friends
                                        where friend.UserId == userId && friend.IsAccepted == true
                                        join user in m_DataContext.Users on friend.FriendId equals user.UserId
                                        select user;
            if (amount != -1)
            {
                return friends.Take(amount);//temp
            }
            return friends;
        }
        /// <summary>
        /// 删除好友_by cciel
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="friendId"></param>
        public void RemoveFiend(string userId, string friendId)
        {
            IEnumerable<Friend> friends = from f in m_DataContext.Friends
                                          where f.FriendId == friendId && f.UserId == userId
                                          select f;
            foreach (var friend in friends)
            {
                m_DataContext.Friends.DeleteOnSubmit(friend);
            }
            IEnumerable<Friend> friends2 = from f in m_DataContext.Friends
                                           where f.FriendId == userId && f.UserId == friendId
                                           select f;
            foreach (var friend in friends2)
            {
                m_DataContext.Friends.DeleteOnSubmit(friend);
            }
            m_DataContext.SubmitChanges();
            //Friend friend = m_DataContext.Friends.Single<Friend>(
        }
    }
}
